package by.bsu.wp.latextool.converter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

public class LatexAdapter {

	private static String url = "http://sciencesoft.at/latex";
	private static String XML_REQUEST_BEGIN = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
			"<latex ochem=\"false\"><dev dpi=\"120\">png16m</dev><src><![CDATA[";
	private static String XML_REQUEST_END = "]]></src><embeddedData>false</embeddedData></latex>";

	public String requestImage(String latexContent) {
		String resultImageUrl = null;
		try {
			HttpClientBuilder builder = HttpClientBuilder.create();
			HttpClient httpClient = builder.build();
			HttpPut putRequest = new HttpPut(url);
			String requestXml = XML_REQUEST_BEGIN + latexContent + XML_REQUEST_END;
			StringEntity input = new StringEntity(requestXml);
			input.setContentType("text/xml; charset=utf-8");
			putRequest.setEntity(input);
			HttpResponse response = httpClient.execute(putRequest);
			HttpEntity respEntity = response.getEntity();
			InputStream contentInputStream = respEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(contentInputStream));
			String line = null, responseContent = "";
			while ((line = reader.readLine()) != null) {
				responseContent += line;
			}
			System.out.println(responseContent);
			
			Pattern pattern = Pattern.compile("<url>([\\w\\p{Punct}]*)</url>");
			Matcher matcher = pattern.matcher(responseContent); matcher.find();
			resultImageUrl = matcher.group(1);
			
		} catch (UnsupportedEncodingException exception) {
			// TODO Auto-generated catch block
			exception.printStackTrace();
		} catch (ClientProtocolException exception) {
			// TODO Auto-generated catch block
			exception.printStackTrace();
		} catch (IOException exception) {
			// TODO Auto-generated catch block
			exception.printStackTrace();
		} catch (IllegalStateException exception) {
			// TODO Auto-generated catch block
			exception.printStackTrace();
		}
		return resultImageUrl;
	}
}
